package com.bodacn.cutacc;


import android.app.Activity;
import android.app.AlertDialog;
import android.app.DatePickerDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Color;
import android.graphics.drawable.BitmapDrawable;
import android.media.Ringtone;
import android.media.RingtoneManager;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import androidx.fragment.app.Fragment;
import android.text.InputType;
import android.text.format.DateFormat;
import android.util.DisplayMetrics;
import android.util.Log;
import android.util.TypedValue;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.TextView;
import android.widget.Toast;

import com.bodacn.keypoint.R;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.lang.reflect.Field;
import java.math.BigDecimal;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.sql.Statement;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.locks.ReentrantLock;
import java.util.regex.Matcher;
import java.util.regex.Pattern;


import static android.view.ViewGroup.LayoutParams.MATCH_PARENT;
import static com.bodacn.cutacc.BaseRequest.postJsonData;


/**
 * A simple {@link Fragment} subclass.
 */
public class FragmentA extends Fragment implements View.OnClickListener, View.OnLongClickListener {
    public static String TAG=FragmentB.class.getName();
    public static final int msgFocusBarcode = 1001;
    public static final int MSG_ApiResult = 9002;
    public static final int MSG_DetailOver =9003;
    public static final int MSG_ERRMSG =9008;
    ReentrantLock reentrantLock = new ReentrantLock();
    //用于将Activity中的参数传给Fragment
    private Map<String,Object> fragmentParams=new HashMap<String,Object>();
    //用于与主Activity通讯;
    private Handler mainHandler;
    SQLiteDatabase tmpdb;
    //全局变量
    PopupWindow popupWindow;
    Toast curToast;

    JSONArray detailJson;
    String PrBarcode="";
    Button btn_find;
    EditText edit_queryDate;
    ListView lv_Detail;
    private ProgressDialog waitDialog = null;



    @Override
    public void onDetach() {
        super.onDetach();
    }

    //图表标识
    private boolean hasAxes = true;
    private boolean hasPoints = true;
    private boolean hasLines = true;
    private boolean isCubic = false;
    private boolean hasLabels = false;
    boolean AllowScan=true;

    //判断是否为数字，不然不转
    public static boolean isNumeric(String str){
        try {
            new BigDecimal(str);
            return true;
        } catch (Exception e) {
            return false;
        }
    }

    @Override
    public boolean onLongClick(View view) {
        switch (view.getId()) {

            default:
                break;
        }
        return false;
    }



    public FragmentA() {
        // Required empty public constructor
    }


    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //得到Activity的Handler,用于发消息给主Activity;
        //全局App;
        try {

            detailJson=new JSONArray("[]");
        } catch (JSONException e) {
            e.printStackTrace();
        }
        System.out.println(TAG+"onCreate-------------------------------------1");
        //创建适配器
        MainActivity activity=(MainActivity) getActivity();
        mainHandler=activity.mainHandler;
        //加接口监听
        activity.setTransParamsListenerA(new MainActivity.OnTransParamsListenerA() {
            @Override
            public void TransParams(Map<String, Object> mParams) {
                if (mParams!=null) {
                    try {
                        System.out.println(mParams);
                        String paramComm= mParams.get("ParamComm").toString();
                        if (paramComm=="LoginParam")
                        {
                            Log.d(this.getClass().getName(),"LoginParam------------------>2");
                            //发消息置焦点
                            Message msg =new Message();
                            msg.what = msgFocusBarcode;
                            fragmentHandler.removeMessages(msg.what);
                            fragmentHandler.sendMessage(msg);
                        }

                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }
        });
        System.out.println(TAG+"onCreate-------------------------------------2");
    }

    /**
     * 隐藏虚拟按键，并且全屏
     */
    protected void hideBottomUIMenu() {
        //隐藏状态栏和底部虚拟按键
        View decorView = getActivity().getWindow().getDecorView();
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            int flag = View.SYSTEM_UI_FLAG_LAYOUT_STABLE
                    | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
                    | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION
                    | View.SYSTEM_UI_FLAG_FULLSCREEN
                    | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY;
            decorView.setSystemUiVisibility(flag);
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View root = inflater.inflate(R.layout.fragment_a, container, false);
        InitView(root);
        System.out.println(this.getClass().getName()+"_onCreateView");
        return root;
    }
    //初始化;
    public void InitView(View view){
        //提示框pd=new ProgressDialog(this);
        waitDialog= new ProgressDialog(getContext());
        waitDialog.setTitle(getString(R.string.SystemHint));
        btn_find=view.findViewById(R.id.btn_find);
        btn_find.setOnClickListener(this);
        lv_Detail=view.findViewById(R.id.lv_Detail);
        //文本框
        edit_queryDate = (EditText) view.findViewById(R.id.edit_queryDate);
        edit_queryDate.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {final Calendar calendar = Calendar.getInstance();
                final DatePickerDialog mDialog = new DatePickerDialog(getContext(), null, calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH), calendar.get(Calendar.DAY_OF_MONTH));
                mDialog .setButton(DialogInterface.BUTTON_POSITIVE,"完成",new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        DatePicker datePicker = mDialog.getDatePicker();
                        int year = datePicker.getYear();
                        int month = datePicker.getMonth();
                        int day = datePicker.getDayOfMonth();
                        calendar.set(year,month,day);
                        edit_queryDate.setText(DateFormat.format("yyyy-MM-dd", calendar));
                    }
                });
                mDialog.setButton(DialogInterface.BUTTON_NEGATIVE,"取消",new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        System.out.println("cancel~~cancel~~");
                    }
                });
                mDialog.setTitle("选择查询起始日期");
                mDialog.show();
            }
        });
        edit_queryDate.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                Log.d("edit_startDate","onFocusChange");
                if (hasFocus == true) {
                    hideIM(v);
                }
            }
        });
        //置日期初始值;
        Date curDate = new Date(System.currentTimeMillis());
        String EndDateStr=(String) DateFormat.format("yyyy-MM-dd", new Date(curDate.getTime()));
        edit_queryDate.setText(EndDateStr);
        //初始提醒;
        curToast = Toast.makeText(getContext(), "", Toast.LENGTH_SHORT);

    }


    //插放音乐;
    private void playRingtone(){
        Uri notification = Uri.parse("android.resource://"+getActivity().getPackageName()+"/"+R.raw.scan);
        Ringtone r = RingtoneManager.getRingtone(getActivity(), notification);
        r.play();

    }

    @Override
    public void onResume() {
        super.onResume();
        hideBottomUIMenu();
    }




    // 隐藏手机键盘
    private void hideIM(View edt) {
        try {
            InputMethodManager im = (InputMethodManager) getActivity().getSystemService(Activity.INPUT_METHOD_SERVICE);
            IBinder windowToken = edt.getWindowToken();
            if (windowToken != null) {
                im.hideSoftInputFromWindow(windowToken, 0);
            }
        } catch (Exception e) {

        }
    }

    @Override
    public void onClick(View v) {
        hideIM(v);
        Intent tmpintent;
        Bundle paramBundle = new Bundle();
        switch (v.getId()){
            case R.id.btn_find:
                waitDialog.setMessage("查询中,请稍等...");
                GetDetail(edit_queryDate.getText().toString()+" 00:00:00");
                break;

            default:
                break;
        }
    }

    //dp 转换成px
    public int dp2px(float dp)
    {
        return (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dp, getResources().getDisplayMetrics());
    }

    //判断是否为数字
    public static boolean isNumer(String str) {
        Pattern pattern = Pattern.compile("-?[0-9]+\\.?[0-9]+");
        Matcher isNum = pattern.matcher(str);
        if (!isNum.matches()) {
            return false;
        }
        return true;
    }
    //从字符串转颜色
    //从字符串转颜色
    private int GetColorValue(String paramColor){
        int PenColor=Color.WHITE;
        String StrPenColor=paramColor;
        if ((StrPenColor.indexOf("#")==0)&&(StrPenColor.length()==7)){
            int testColor=Integer.parseInt(StrPenColor.substring(1),16);
            int red = (testColor & 0xff0000) >> 16;
            int green = (testColor & 0x00ff00) >> 8;
            int blue = (testColor & 0x0000ff);
            PenColor=Color.rgb(red, green, blue);
        }else {
            if (isNumer(StrPenColor)) {
                int testColor = Integer.parseInt(StrPenColor);
                int red = (testColor & 0xff0000) >> 16;
                int green = (testColor & 0x00ff00) >> 8;
                int blue = (testColor & 0x0000ff);
                PenColor = Color.rgb(red, green, blue);
            } else {
                if (StrPenColor.equals("Black") == true)
                    PenColor = Color.BLACK;
                if (StrPenColor.equals("Blue") == true)
                    PenColor = Color.BLUE;
                if (StrPenColor.equals("Yellow") == true)
                    PenColor = Color.YELLOW;
                if (StrPenColor.equals("Red") == true)
                    PenColor = Color.RED;
                if (StrPenColor.equals("Green") == true)
                    PenColor = Color.GREEN;
                if (StrPenColor.equals("Gray") == true)
                    PenColor = Color.LTGRAY;
                if (StrPenColor.equals("White") == true)
                    PenColor = Color.WHITE;
            }
        }
        return PenColor;
    }

    /**
     * 定义一个Handler用于接收Fragment发出来的指令
     */
    public Handler fragmentHandler=new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if(msg!=null){
                if (waitDialog.isShowing()==true) waitDialog.cancel();
                String tmpValue;
                Bundle bundle;
                //任意消息来均置焦点
                int msgId = msg.what;
                System.out.println("收到的消息是："+msg.what);
                try {
                    switch (msgId) {

                        case MSG_ERRMSG:
                            Bundle bundle1=msg.getData();
                            String mesg=bundle1.getString("MSG","");
                            curToast.setText(mesg);
                            curToast.show();
                        case MSG_ApiResult:
                            System.out.println(msg.obj);
                            System.out.println(msg.arg1);
                            if (msg.arg1==BaseRequest.HAND_REQUEST_SUCCESS) {
                                try {
                                    JSONObject jsonObject=new JSONObject(msg.obj.toString());
                                    if (jsonObject.has("code")){
                                        if (jsonObject.getString("code").equals("200")){
                                            detailJson=jsonObject.getJSONArray("data");
                                            System.out.println("detailJson:"+detailJson);
                                            //显示明细数据
                                            if (lv_Detail!=null) {
                                                DetailListAdapter detailListAdapter = new DetailListAdapter(getContext());
                                                lv_Detail.setAdapter(detailListAdapter);
                                            }
                                        }
                                    } else{
                                        Message message = new Message();
                                        message.what =MSG_ERRMSG;
                                        bundle=new Bundle();
                                        bundle.putString("Hint","未正确返回结果");
                                        message.setData(bundle);
                                        fragmentHandler.sendMessage(message);
                                    }
                                } catch (JSONException e) {
                                    e.printStackTrace();
                                    Message message = new Message();
                                    message.what =MSG_ERRMSG;
                                    bundle=new Bundle();
                                    bundle.putString("Hint",msg.obj+"\r\n"+e.getMessage());
                                    message.setData(bundle);
                                    fragmentHandler.sendMessage(message);
                                }
                            } else{
                                Message message = new Message();
                                message.what =MSG_ERRMSG;
                                bundle=new Bundle();
                                bundle.putString("Hint",msg.obj.toString());
                                message.setData(bundle);
                                fragmentHandler.sendMessage(message);
                            }
                            break;
                        case MSG_DetailOver:

                            break;

                        default:
                            break;
                    }
                }catch (Exception e){
                    e.printStackTrace();
                }
            }
        }
    };

    //获取明细数据
    private void GetDetail(String paramData) {
        JSONObject jsonObject=new JSONObject();
        try {
            jsonObject.put("appId","FLDayPlan");
            jsonObject.put("appKey","FLDayPlan");
            jsonObject.put("bbm",MainApplication.bbm);
            jsonObject.put("kdrq",paramData);
            jsonObject.put("platform","PAD");
            jsonObject.put("token","7e0daaaed1a1543727122788a4e5398e7c23e88b075a32e3922a6d96b5642db9");
            jsonObject.put("version","1.0");
        } catch (JSONException e) {
            e.printStackTrace();
        }
        System.out.println("请求参数:"+jsonObject.toString());
        postJsonData("http://10.10.31.87:8081/szapi/third/BdFzzt/listBdFlplanDO",
                jsonObject.toString(),fragmentHandler,MSG_ApiResult);

    }




    //订单表格适配器;
    public final class DetailListAdapter extends BaseAdapter {
        private LayoutInflater inflater;
        public DetailListAdapter(Context context) {
            inflater = (LayoutInflater) context
                    .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        }
        @Override
        public int getCount() {
            return detailJson.length();
        }

        @Override
        public Object getItem(int position) {
            try {
                return detailJson.get(position);
            } catch (JSONException e) {
                e.printStackTrace();
            }
            return null;
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            if (convertView == null) convertView = inflater.inflate(R.layout.fragment_a_listitem, null, false);


            String tmpValue;
            try {
                Log.d(TAG,"getView()----------------------------------------------------->"+position);
                TextView tv = (TextView) convertView.findViewById(R.id.tv_bh);// 显示文字
                if (detailJson.optJSONObject(position).has("bh")) tv.setText(detailJson.optJSONObject(position).get("bh").toString());
                tv = (TextView) convertView.findViewById(R.id.tv_dbh);// 显示文字
                if (detailJson.optJSONObject(position).has("dbh")) tv.setText(detailJson.optJSONObject(position).get("dbh").toString());
                tv = (TextView) convertView.findViewById(R.id.tv_poh);// 显示文字
                if (detailJson.optJSONObject(position).has("poh")) tv.setText(detailJson.optJSONObject(position).get("poh").toString());
                tv = (TextView) convertView.findViewById(R.id.tv_hyh);// 显示文字
                if (detailJson.optJSONObject(position).has("hyh")) tv.setText(detailJson.optJSONObject(position).get("hyh").toString());
                tv = (TextView) convertView.findViewById(R.id.tv_hh);// 显示文字
                if (detailJson.optJSONObject(position).has("hh")) tv.setText(detailJson.optJSONObject(position).get("hh").toString());
                tv = (TextView) convertView.findViewById(R.id.tv_gh);// 显示文字
                if (detailJson.optJSONObject(position).has("gh")) tv.setText(detailJson.optJSONObject(position).get("gh").toString());
                tv = (TextView) convertView.findViewById(R.id.tv_psxx);// 显示文字
                if (detailJson.optJSONObject(position).has("psxx")) tv.setText(detailJson.optJSONObject(position).get("psxx").toString());
                tv = (TextView) convertView.findViewById(R.id.tv_sh);// 显示文字
                if (detailJson.optJSONObject(position).has("sh")) tv.setText(detailJson.optJSONObject(position).get("sh").toString());
                tv = (TextView) convertView.findViewById(R.id.tv_sc);// 显示文字
                if (detailJson.optJSONObject(position).has("sc")) tv.setText(detailJson.optJSONObject(position).get("sc").toString());
                tv = (TextView) convertView.findViewById(R.id.tv_cm);// 显示文字
                if (detailJson.optJSONObject(position).has("cm")) tv.setText(detailJson.optJSONObject(position).get("cm").toString());
                tv = (TextView) convertView.findViewById(R.id.tv_cplx);// 显示文字
                if (detailJson.optJSONObject(position).has("cplx")) tv.setText(detailJson.optJSONObject(position).get("cplx").toString());
                tv = (TextView) convertView.findViewById(R.id.tv_jhlx);// 显示文字
                if (detailJson.optJSONObject(position).has("jhlx")) tv.setText(detailJson.optJSONObject(position).get("jhlx").toString());
                tv = (TextView) convertView.findViewById(R.id.tv_zps);// 显示文字
                if (detailJson.optJSONObject(position).has("zps")) tv.setText(detailJson.optJSONObject(position).get("zps").toString());
                tv = (TextView) convertView.findViewById(R.id.tv_flmc);// 显示文字
                if (detailJson.optJSONObject(position).has("flmc")) tv.setText(detailJson.optJSONObject(position).get("flmc").toString());
                tv = (TextView) convertView.findViewById(R.id.tv_jgmc);// 显示文字
                if (detailJson.optJSONObject(position).has("jgmc")) tv.setText(detailJson.optJSONObject(position).get("jgmc").toString());
                tv = (TextView) convertView.findViewById(R.id.tv_sam);// 显示文字
                if (detailJson.optJSONObject(position).has("sam")) tv.setText(detailJson.optJSONObject(position).get("sam").toString());
            } catch (JSONException e) {
                e.printStackTrace();
                System.out.println(e.getMessage());
            }
            Log.d(TAG,"DetailGridAdapter_position:"+position);
            return convertView;
        }
    }



    @Override
    public void onStart() {
        super.onStart();

    }

    @Override
    public void onPause() {
        super.onPause();
    }

    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);

    }
}
